import { HvigorNode, HvigorPlugin, Json5Reader } from '@ohos/hvigor';
import * as zip from 'unzipper'
import * as fs from 'fs'
import path from 'path';
import { log } from './ModularityGeneratePlugin';

export class CommonRouterModule {

    static checkCreate(node: HvigorNode, complete: () => void) {
        const projectPath = node.getNodePath()
        const commonRouterPath = projectPath + "/common_router"
        let isDirectory = false
        try {
            const stats = fs.statSync(commonRouterPath)
            isDirectory = stats.isDirectory()
        } catch {
            isDirectory = false
        }
        if (isDirectory) {
            log("工程" + projectPath + "- 存在 common_router 模块")
            complete()
        } else {
            log("工程" + projectPath + "- 不存在 common_router 模块")
            this.unzipModule(projectPath, complete)
        }
    }

    static unzipModule(projectPath: string, complete: () => void) {
        const unzipFile = __dirname + "/common_router.zip"
        const directory = zip.Open.file(unzipFile).then(directory => {
            directory.extract({ path: projectPath }).then(() => {
                log("创建common_module模块")
                // 删除mac 解压附带产物
                this.deleteLocalFolder(projectPath + "/__MACOSX")
                this.addModuleToProjectBuildProfile(projectPath)
                this.addCommonRouterProjectPackageOverrides(projectPath)
                complete()
            })
        })
    }




    static addModuleToProjectBuildProfile(projectPath: string) {
        const packageJson5 = Json5Reader.getJson5Obj(projectPath + "/build-profile.json5", "utf8")

        const packageJson5Obj = JSON.parse(JSON.stringify(packageJson5))

        const modules = packageJson5Obj.modules

        const commonRouterModule = modules.find((item: any) => item.name == "common_router")

        if (!commonRouterModule) {
            log("配置工程oh-package.json5,添加common-router 依赖")
            modules.push({
                name: "common_router",
                srcPath: "./common_router",
                targets: [
                    {
                        name: "default",
                        applyToProducts: [
                            "default"
                        ]
                    }
                ]
            })
            fs.writeFileSync(projectPath + "/build-profile.json5", JSON.stringify(packageJson5Obj, null, 2))
        }
    }

    static addCommonRouterProjectPackageOverrides(projectPath: string) {
        log("添加common_router 依赖到工程级 oh-package.json5 的 overrides 中")
        const packageJson5 = Json5Reader.getJson5Obj(projectPath + "/oh-package.json5", "utf8")
        const packageJson5Obj = JSON.parse(JSON.stringify(packageJson5))
        log(JSON.stringify(packageJson5,null,2))
        if (!packageJson5Obj.overrides || !packageJson5Obj.overrides["@satis/common_router"]) {
            if (!packageJson5Obj.overrides) {
                packageJson5Obj.overrides = {}
            }
            packageJson5Obj.overrides["@satis/common_router"] = "file:common_router"
            fs.writeFileSync(projectPath + "/oh-package.json5", JSON.stringify(packageJson5Obj, null, 2))
        }
    }


    static deleteLocalFolder(folderPath: string): void {
        if (!fs.existsSync(folderPath)) {
            log('文件夹不存在，无法删除');
            return;
        }

        // 读取文件夹内容并递归删除
        fs.readdirSync(folderPath).forEach((file) => {
            const currentPath = path.join(folderPath, file);
            if (fs.lstatSync(currentPath).isDirectory()) {
                // 递归删除子文件夹
                this.deleteLocalFolder(currentPath);
            } else {
                // 删除文件
                fs.unlinkSync(currentPath);
            }
        });

        // 删除文件夹
        fs.rmdirSync(folderPath);
    }
}